import numpy


def _get_near_points(border, target_point, fit_window):
    target_x, target_y = target_point
    top, bottom, left, right = fit_window
    near_points = []  # 拟合窗内的点
    for x, y in border:
        delta_x = x - target_x
        delta_y = y - target_y
        if 0 <= delta_x < right or -left < delta_x < 0:
            if 0 <= delta_y < top or -bottom < delta_y < 0:
                near_points.append((x, y))
    return near_points


def get_tangent(border, target_point, fit_window, poly_num=3):
    target_x, target_y = target_point
    near_points = _get_near_points(border, target_point, fit_window)
    near_points = list(map(list, zip(*near_points)))
    poly = numpy.polyfit(*near_points, poly_num)  # 使用多项式拟合
    dp = numpy.poly1d(poly).deriv()
    k = dp(target_x)
    b = target_y - k * target_x
    return k, b
